package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.adapter.VpCommonAdapter;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PopUpManager;
import com.ycsj.common.manager.TimerCountManager;
import com.ycsj.common.utils.DateUtils;
import com.ycsj.common.utils.DeviceUtils;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.StateBarUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.ZzHorizontalProgressBar;
import com.ycsj.common.view.vp.SuperViewPager;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.TkKeys;
import com.ycsj.goldmedalnewconcept.common.bean.Res;
import com.ycsj.goldmedalnewconcept.common.bean.SubListBean;
import com.ycsj.goldmedalnewconcept.common.bean.TkItemBean;
import com.ycsj.goldmedalnewconcept.common.http.HttpCallBack;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.TimeCount;
import com.ycsj.goldmedalnewconcept.teacher.adapter.PanelGvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.bean.CommitAnswerInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.CommitInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.PanelInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.Question;
import com.ycsj.goldmedalnewconcept.teacher.fragment.ClozeTestFragment;
import com.ycsj.goldmedalnewconcept.teacher.fragment.FillingSentenceFragment;
import com.ycsj.goldmedalnewconcept.teacher.fragment.ReadEssayQuestionFragment;
import com.ycsj.goldmedalnewconcept.teacher.fragment.ReadGapFillingFragment;
import com.ycsj.goldmedalnewconcept.teacher.fragment.ReadJudgeFragment;
import com.ycsj.goldmedalnewconcept.teacher.fragment.ReadSingleChooseFragment;
import com.ycsj.goldmedalnewconcept.teacher.fragment.SingleChoiceFragment;
import com.ycsj.goldmedalnewconcept.teacher.fragment.TkSentenceCompleFragment;
import com.ycsj.goldmedalnewconcept.teacher.fragment.TranslateFragment;
import com.ycsj.goldmedalnewconcept.teacher.manager.QuestionsManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.itangqi.waveloadingview.WaveLoadingView;
import okhttp3.Call;

/**
 * 教师端题库查看题目界面
 */
public class TeacherTkMainActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    private ImageView ivBack;
    private TextView tvTitle;
    private ImageView lvEdit;
    private ImageView ivChooseNum;
    private RelativeLayout rlLoading;
    private RelativeLayout rlContent;

    //进度条
    private ZzHorizontalProgressBar pb;

    //显示进度条的文本
    private TextView tvPb;

    //分析按钮
    private ImageView iv_fenxi;

    private SuperViewPager vp;

    //填充的Fragment集合
    private List<Fragment> mFragments;

    //ViewPager的适配器
    private VpCommonAdapter adapter;

    //记录ViewPager的页面位置值
    private int currPos = 0;

    //控制顶部的答题面板是否可以点击的标识
    private boolean isArrowClick = false;

    //面板的数据模型
    private List<PanelInfo> panelInfos;

    //传递的请求参数和区别的类型
    private String exam_id;

    // 学生做题0  1学生查看解析 2老师查看题和解析-有人做(全校正确率和小题正确率都显示)
    // 3(习题分析)老师查看题和解析-没人做,对应查看单题
    private String type;

    //传递的单元号
    private String unit;

    //老师账号
    private String ttel;

    //学生姓名
    private String sname;

    //总数
    private String total;

    //班级
    private String classnum;

    //是否需要重新计时的标识
    public static boolean isNeedCountTime = true;

    //学生答题切换面板需要显示的数据集合
    private List<CommitAnswerInfo> commitAnswerInfos;

    //接口返回的数据对象
    private Question info;

    private LinearLayout ll_timer;
    private LinearLayout ll_pb;

    //计时器
    private Chronometer timer;

    //设置isNeedCountTime的方法
    public static void setIsNeedCountTime(boolean isNeedCountTime) {
        TeacherTkMainActivity.isNeedCountTime = isNeedCountTime;
    }

    //提供给获取计时器控件的方法
    public Chronometer getTimer() {
        return timer;
    }

    public void setTimer(Chronometer timer) {
        this.timer = timer;
    }

    {

    }

    /**
     * 从教师端跳转到当前界面的方法
     *
     * @param exam_id 当前页面请求的参数
     * @param type    传递的区分的类型
     * @param unit    传递的单元号,没有单元号的情况传""即可
     */
    public static void goActivity(Context context, String exam_id, String type, String unit, String total) {
        Intent intent = new Intent(context, TeacherTkMainActivity.class);
        intent.putExtra("exam_id", exam_id);
        intent.putExtra("type", type);
        intent.putExtra("unit", unit);
        intent.putExtra("total", total);
        context.startActivity(intent);
    }


    /**
     * 从学生端跳转到当前界面的方法
     *
     * @param exam_id 当前页面请求的参数
     * @param type    传递的区分的类型
     * @param unit    传递的单元号,没有单元号的情况传""即可
     */
    public static void studentGoActivity(Context context, String exam_id, String type, String unit
            , String ttel, String sname, String classnum) {
        Intent intent = new Intent(context, TeacherTkMainActivity.class);
        intent.putExtra("exam_id", exam_id);
        intent.putExtra("type", type);
        intent.putExtra("unit", unit);
        intent.putExtra("ttel", ttel);
        intent.putExtra("sname", sname);
        intent.putExtra("classnum", classnum);
        context.startActivity(intent);
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_tk_main;
    }

    @Override
    protected void init() {

        //设置状态栏颜色
        StateBarUtil.customImmerseBar(this);

        //初始化视图
        initView();

        //接收数据
        initIntent();

        //习题分析界面标题栏
        initTitle();

        //请求数据
        http();

    }


    /**
     * 初始化视图
     */
    private void initView() {
        lvEdit = findViewById(R.id.lv_edit);
        tvTitle = findViewById(R.id.tv_title);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        lvEdit.setOnClickListener(this);
        ivChooseNum = findViewById(R.id.lv_edit);
        ivChooseNum.setOnClickListener(this);
        vp = findViewById(R.id.vp);
        rlLoading = findViewById(R.id.rl_loading);
        rlLoading.setVisibility(View.VISIBLE);
        pb = findViewById(R.id.pb);
        tvPb = findViewById(R.id.tv_pb);
        rlContent = findViewById(R.id.rl_content);
        rlContent.setVisibility(View.GONE);
        timer = findViewById(R.id.timer);
        ll_timer = findViewById(R.id.ll_timer);
        ll_pb = findViewById(R.id.ll_pb);
        iv_fenxi = findViewById(R.id.iv_fenxi);
        iv_fenxi.setOnClickListener(this);
    }

    /**
     * 习题分析标题栏
     */
    private void initTitle() {
        lvEdit.setVisibility(View.VISIBLE);
        lvEdit.setImageResource(R.drawable.panel_question);
    }

    /**
     * 接收数据
     */
    private void initIntent() {
        //获取页面请求参数
        exam_id = getIntent().getStringExtra("exam_id");
        type = getIntent().getStringExtra("type");
        unit = getIntent().getStringExtra("unit");
        ttel = getIntent().getStringExtra("ttel");
        sname = getIntent().getStringExtra("sname");
        total = getIntent().getStringExtra("total");
        classnum = getIntent().getStringExtra("classnum");

        //设置标题
        if (!TextUtils.isEmpty(unit)) {
            tvTitle.setText("Unit" + unit);
        } else {
            tvTitle.setText("习题分析");
        }
//
//        if ("0".equals(type)) {
//            //初始化计时器
//            TimeCount.init();
//
//            //显示倒计时
//            ll_timer.setVisibility(View.VISIBLE);
//
//            //启动计时器
//            TimerCountManager.startTimer(true, timer);
//        } else {
//            //不显示倒计时
//            ll_timer.setVisibility(View.GONE);
//        }

        if ("2".equals(type) || "3".equals(type)) {
            //显示习题分析
            iv_fenxi.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 请求已完成服务器数据的方法
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        if ("0".equals(type)) {
            map.put("jobmsg", "2");
            map.put("exam_id", exam_id);
            map.put("option", "0");
            map.put("school", AccountUtils.getSchoolId(this));
        } else if ("1".equals(type)) {
            map.put("jobmsg", "6");
            map.put("exam_id", exam_id);
        } else if ("2".equals(type) || "3".equals(type)) {
            map.put("jobmsg", "2");
            map.put("exam_id", exam_id);
            map.put("option", "1");
            map.put("school", AccountUtils.getSchoolId(this));
        }

        //        Log.i("test", "exam_id=" + exam_id + "&school=" + AccountUtils.getSchoolId(this));

        HttpUtils.post(HttpAddress.TKCONTENT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {
                if (!TextUtils.isEmpty(response)) {
                    rlLoading.setVisibility(View.GONE);

                    if ("0".equals(type)) {
                        //初始化计时器
                        TimeCount.init();

                        //显示倒计时
                        ll_timer.setVisibility(View.VISIBLE);

                        //启动计时器
                        TimerCountManager.startTimer(true, timer);
                    } else {
                        //不显示倒计时
                        ll_timer.setVisibility(View.GONE);
                    }

                    try {
                        info = GsonUtil.jsonToBean(response, Question.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if (1 == info.getState()) {
                            //状态码为1返回成功
                            rlContent.setVisibility(View.VISIBLE);
                            if (null != info) {

                                //取所有的题型数据
                                List<TkItemBean> questions = info.getList();

                                if (questions != null && questions.size() != 0) {

                                    //根据返回的题型来初始化Fragment
                                    initFragments(questions);

                                    if ("0".equals(type)) {
                                        //学生未作答初始化答题面板
                                        initNoCompletePaneInfos(questions);
                                    } else if ("1".equals(type)) {
                                        //学生查看解析和老师查看某个学生的解析
                                        initHasCompletePaneInfos(questions);
                                    } else if ("2".equals(type) || "3".equals(type)) {
                                        //老师查看题和解析-有人做或没人做
                                        initNoCompletePaneInfos(questions);
                                    }
                                } else {
                                    //没有题目的情况
                                    ToastUtils.showShort("暂无题目");
                                    lvEdit.setVisibility(View.GONE);
                                    //显示倒计时
                                    ll_timer.setVisibility(View.GONE);
                                    ll_pb.setVisibility(View.GONE);
                                }
                            }
                        } else {
                            //服务器返回异常状态码
                            ToastUtils.showShort("服务器异常,返回异常码是:" + info.getState());
                        }
                    }
                }
            }
        });
    }

    /**
     * 学生查看解析和老师查看某个学生的解析
     *
     * @param questions
     */
    private void initHasCompletePaneInfos(List<TkItemBean> questions) {

        panelInfos = new ArrayList<>();

        for (int i = 0; i < questions.size(); i++) {

            PanelInfo panelInfo = new PanelInfo();

            //题目类型
            panelInfo.question_type = questions.get(i).getTypeid();

            //题目编号
            panelInfo.question_id = questions.get(i).getId_D();

            //创建每个大题包含的小题信息
            panelInfo.commitAnswerInfos = getAllCompleteQuestions(i, questions.get(i));

            panelInfos.add(panelInfo);
        }

        //创建面板展示的数据信息,这里规则是显示所有小题信息
        commitAnswerInfos = new ArrayList<>();

        for (int i = 0; i < panelInfos.size(); i++) {
            commitAnswerInfos.addAll(panelInfos.get(i).commitAnswerInfos);
        }


        LogUtils.iTag("test", GsonUtil.listToJson(commitAnswerInfos));


        //面板数据加载完成后可以点击
        isArrowClick = true;

    }

    /**
     * 学生未作答初始化答题面板信息
     *
     * @param questions
     */
    private void initNoCompletePaneInfos(List<TkItemBean> questions) {

        panelInfos = new ArrayList<>();

        for (int i = 0; i < questions.size(); i++) {

            PanelInfo panelInfo = new PanelInfo();

            //题目类型
            panelInfo.question_type = questions.get(i).getTypeid();

            //题目编号
            panelInfo.question_id = questions.get(i).getId_D();

            //默认都是未完成的状态
            panelInfo.state = 0;

            //默认给0,检查大题的所有小题,如果所有小题都回答正确,该值给1,如果所有小题有一个题,则该值给0
            panelInfo.qa_answer = 0;

            //创建每个大题包含的小题信息
            panelInfo.commitAnswerInfos = getAllQuestions(i, questions.get(i));

            //回传给服务器的每个小题的正确答案
            panelInfo.right_answer = sysAnswer(panelInfo.commitAnswerInfos);

            panelInfos.add(panelInfo);
        }

        //创建面板展示的数据信息,这里规则是显示所有小题信息
        commitAnswerInfos = new ArrayList<>();

        for (int i = 0; i < panelInfos.size(); i++) {
            commitAnswerInfos.addAll(panelInfos.get(i).commitAnswerInfos);
        }


        //面板数据加载完成后可以点击
        isArrowClick = true;
    }

    /**
     * 学生查看或者老师查看某个学生面板信息
     *
     * @param postion    小题所属大题在所有题目中的位置
     * @param tkItemBean
     * @return
     */
    private List<CommitAnswerInfo> getAllCompleteQuestions(int postion, TkItemBean tkItemBean) {

        LogUtils.iTag("test", "题目数据是：" + GsonUtil.objectToJson(tkItemBean));

        List<CommitAnswerInfo> commitAnswerInfos = new ArrayList<>();

        //获取每个大题的所有小题集合
        List<SubListBean> sub_list = tkItemBean.getSub_list();

        int size = sub_list.size();

        //获取每个大题的提醒id
        String typeid = tkItemBean.getTypeid();

        for (int i = 0; i < size; i++) {
            CommitAnswerInfo info = new CommitAnswerInfo();
            if ("1".equals(sub_list.get(i).getStu_anwer())) {
                info.isRight = true;
            } else {
                info.isRight = false;
            }

//            if (sub_list.get(i).getStu_option().equals(sub_list.get(i).getOption())) {
//                info.isRight = true;
//            } else {
//                info.isRight = false;
//            }

            info.num = i + "";//编号
            info.index = postion + "";//小题所属大题在所有题目中的位置
            info.score = Integer.parseInt(sub_list.get(i).getScore());//每个小题的分数
            info.rightAnser = sub_list.get(i).getOption();//正确答案
            info.onwAnswer = sub_list.get(i).getStu_option();//每个小题自己的作答,默认是空
            info.typeid = typeid;//每个小题的题目类型,跟大题所属的题目类型一致
            if (size == 1) {
                //表示该大题只有1个小题
                info.name = (postion + 1) + "";
            } else {
                //表示该大题中有多个小题
                info.name = (postion + 1) + "-" + (i + 1);
            }

            commitAnswerInfos.add(info);
        }

        return commitAnswerInfos;
    }


    /**
     * 学生答题创建每个大题包含的小题信息
     *
     * @param postion    小题所属大题在所有题目中的位置
     * @param tkItemBean
     * @return
     */
    private List<CommitAnswerInfo> getAllQuestions(int postion, TkItemBean tkItemBean) {

        List<CommitAnswerInfo> commitAnswerInfos = new ArrayList<>();

        //获取每个大题的所有小题集合
        List<SubListBean> sub_list = tkItemBean.getSub_list();

        //获取每个大题的提醒id
        String typeid = tkItemBean.getTypeid();
        int size = sub_list.size();

        for (int i = 0; i < size; i++) {
            CommitAnswerInfo info = new CommitAnswerInfo();
            info.isRight = false;//默认错误
            info.num = i + "";//编号
            info.index = postion + "";//小题所属大题在所有题目中的位置
            info.score = QuestionsManager.getScore(typeid);//每个小题的分数
            info.rightAnser = sub_list.get(i).getOption();//正确答案
            info.onwAnswer = "";//每个小题自己的作答,默认是空
            info.typeid = typeid;//每个小题的题目类型,跟大题所属的题目类型一致
            if (size == 1) {
                //表示该大题只有1个小题
                info.name = (postion + 1) + "";
            } else {
                //表示该大题中有多个小题
                info.name = (postion + 1) + "-" + (i + 1);
            }

            commitAnswerInfos.add(info);
        }

        return commitAnswerInfos;
    }


    /**
     * 初始化Vp的操作
     */
    private void initVp() {
        adapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(mFragments.size());
    }

    /**
     * ViewPager的滚动监听事件
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        //记录当前ViewPager的位置
        currPos = position;

        //设置进度条的文本显示值
        tvPb.setText((position + 1) + "/" + (mFragments.size()));

        //同时需要设置进度条的值
        pb.setProgress((int) ((float) (position + 1) / (float) (mFragments.size()) * 100));
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.lv_edit) {
            if (isArrowClick) {
                if ("0".equals(type)) {
                    //学生未答题的面板
                    showCommitPanel();
                } else if ("1".equals(type)) {
                    //学生已答题的面板
                    showErrorPanel();
                } else {
                    //老师查看题目(有人做和没人做)
                    showCommitPanel();
                }
            } else {
                ToastUtils.showShort("正在加载数据,请稍候...");
            }
        } else if (id == R.id.iv_fenxi) {
            //习题分析
            TeacherAppraisalTestActivity.startActivity(this, AccountUtils.getSchoolId(this),
                    AccountUtils.getAccount(this), AccountUtils.getTeacherClass(this)
                    , unit, total);
        }
    }

    /**
     * 根据返回的所有题型来创建Fragement
     *
     * @param questions
     */
    private void initFragments(List<TkItemBean> questions) {

        //创建Fragment集合
        mFragments = new ArrayList<>();

        //选词填空(TkChooseWordInBlankFragment)和用单词的适当形式填空(TkWordFormInBlankFragment)
        //遍历集合创建Fragment集合
        if (questions != null && questions.size() != 0) {
            for (int i = 0; i < questions.size(); i++) {
                TkItemBean itemBean = questions.get(i);
                //获取TypeId
                String typeid = itemBean.getTypeid();
                if ("1".equals(typeid)) {
                    //阅读理解判断(已开放)
                    mFragments.add(ReadJudgeFragment.newInstance(itemBean, type, i));
                } else if ("2".equals(typeid)) {
                    //阅读理解填空(已开放)
                    mFragments.add(ReadGapFillingFragment.newInstance(itemBean, type, i));
                } else if ("3".equals(typeid)) {
                    //阅读理解选择(已开放)
                    mFragments.add(ReadSingleChooseFragment.newInstance(itemBean, type, i));
                } else if ("4".equals(typeid)) {
                    //阅读理解问答(已开放)
                    mFragments.add(ReadEssayQuestionFragment.newInstance(itemBean, type, i));
                } else if ("5".equals(typeid)) {
                    //完型填空选择(已开放)
                    mFragments.add(ClozeTestFragment.newInstance(itemBean, type, i));
                } else if ("6".equals(typeid)) {
                    //句子填空一组选择题(已开放)
                    mFragments.add(FillingSentenceFragment.newInstance(itemBean, type, i));
                } else if ("7".equals(typeid)) {
                    //句子填空单个填空(已开放)
                    mFragments.add(TkSentenceCompleFragment.newInstance(itemBean, type, i));
                } else if ("8".equals(typeid)) {
                    //句子改错(未开放)

                } else if ("9".equals(typeid)) {
                    //翻译(已开放)
                    mFragments.add(TranslateFragment.newInstance(itemBean, type, i));

                } else if ("10".equals(typeid)) {
                    //选择 单选题(已开放)
                    mFragments.add(SingleChoiceFragment.newInstance(itemBean, type, i));

                } else if ("11".equals(typeid)) {
                    //连词成句(未开放)

                } else if ("12".equals(typeid)) {
                    //句型转换(未开放)

                } else if ("13".equals(typeid)) {
                    //选词填空 填句子(未开放)

                } else if ("14".equals(typeid)) {
                    //选词填文章 填文章(未开放)
                }
            }

            //初始化Vp的操作
            if (mFragments.size() != 0) {

                //设置默认进度条的值
                pb.setProgress((int) ((float) (1) / (float) (mFragments.size()) * 100));

                //设置当前展示的Vp的页码
                tvPb.setText("1/" + (mFragments.size()));

                initVp();

                //设置Vp的监听
                vp.addOnPageChangeListener(this);
            }
        }
    }


    /**
     * 学生答题的提交面板
     */
    private void showCommitPanel() {

        PopUpManager.showPopByMatchParent(this, R.layout.panel_commit, 0.3f, this, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {

                //展示答题信息的GridView
                GridView gv = view.findViewById(R.id.gv);

                PanelGvAdapter adapter = new PanelGvAdapter(TeacherTkMainActivity.this, type, commitAnswerInfos, R.layout.tk_gv_item_panel);

                gv.setAdapter(adapter);

                LogUtils.iTag("test", commitAnswerInfos);

                adapter.setOnTvClickListener(new PanelGvAdapter.onTvClickListener() {
                    @Override
                    public void onClick(int pos) {
                        //获取小题所属大题在整个题目的位置
                        int postion = Integer.valueOf(commitAnswerInfos.get(pos).index);

                        //定位大题的位置
                        if (postion != currPos) {
                            currPos = postion;
                            vp.setCurrentItem(currPos);
                        }

                        //定位小题所在的位置,先确定大题所处的小题位置,只有大题中有多个小题的才进行翻页处理
                        BusInfo busInfo = new BusInfo();
                        busInfo.type = TkKeys.TKCOMIT;
                        busInfo.bigPos = Integer.parseInt(commitAnswerInfos.get(pos).index);
                        busInfo.postion = Integer.parseInt(commitAnswerInfos.get(pos).num);
                        EventBus.getDefault().post(busInfo);

                        //关闭弹框
                        PopUpManager.dismiss();
                    }
                });

                //提交按钮
                final Button btCommit = view.findViewById(R.id.bt_commit);
                if ("0".equals(type)) {
                    //家长端隐藏提交按钮
                    if ("1".equals(AccountUtils.getRole(TeacherTkMainActivity.this))) {
                        btCommit.setVisibility(View.GONE);
                    } else {

                        btCommit.setVisibility(View.VISIBLE);
                        btCommit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //提交
                                if (!hasDoneOver()) {
                                    ToastUtils.showShort("请完成后再提交");
                                } else {
                                    PopUpManager.dismiss();
                                    btCommit.setClickable(false);

                                    String time = getPostTime();

//                                    LogUtils.iTag("test", "答题时间是:" + time);

                                    int scoretemp = (int) ((Double.parseDouble(getMyScore())
                                            / Double.parseDouble(getTotalScore(panelInfos))) * 100);
                                    //获取总正确率
                                    String score = scoretemp + "";

                                    //上传的json数据
                                    String postJson = getPostJson();

                                    CustomDialogManager.show(TeacherTkMainActivity.this, "提交中...");
                                    Map<String, String> map = new HashMap<>();
                                    map.put("jobmsg", "1");
                                    map.put("ttel", ttel);//老师手机号
                                    map.put("stel", AccountUtils.getAccount(TeacherTkMainActivity.this));//学生手机号
                                    map.put("sname", sname);//学生的姓名
                                    map.put("school", AccountUtils.getSchoolId(TeacherTkMainActivity.this));
                                    map.put("classnum", classnum);
                                    map.put("exam_id", exam_id);
                                    map.put("total_time", time);
                                    map.put("score", score);
                                    map.put("question_list", postJson);

                                    //添加的参数-安卓端
                                    map.put("telOs", "1");

                                    //添加的参数-安卓手机的相关参数
                                    map.put("androidOs", DeviceUtils.getDeviceBrand() + "/" + DeviceUtils.getSysVersion());

                                    LogUtils.iTag("test", "ttel=" + AccountUtils.getTeacher(TeacherTkMainActivity.this)
                                            + "&stel=" + AccountUtils.getAccount(TeacherTkMainActivity.this)
                                            + "&sname=" + sname + "&classnum=" + AccountUtils.getClassNum(TeacherTkMainActivity.this)
                                            + "&exam_id=" + exam_id
                                            + "&total_time=" + time + "&score=" + score + "&usedfor=1&question_list=" + postJson);

                                    HttpUtils.post(HttpAddress.TKCOMMIT, map, this, new HttpCallBack<Res>() {
                                        @Override
                                        public void onSuccess(Res resultInfo) {
                                            CustomDialogManager.dissmiss();
                                            btCommit.setClickable(true);

                                            if (info != null) {
                                                if (info.state == 1) {
                                                    //上传成功
                                                    ToastUtils.showShort("提交成功");
                                                    BusInfo busInfo = new BusInfo();
                                                    busInfo.tkMsg = TkKeys.SUCC;
                                                    EventBus.getDefault().post(busInfo);
                                                    //关闭页面
                                                    finish();
                                                } else {
                                                    ToastUtils.showShort("提交失败,错误码是:" + info.state);
//                                                    ToastUtils.showShort("提交失败,错误码是:" + info.state);
                                                }
                                            }
                                        }

                                        @Override
                                        public void onError(String e) {
                                            CustomDialogManager.dissmiss();
                                            ToastUtils.showShort(BaseApplication.ERROR);
                                            btCommit.setClickable(true);
                                        }
                                    });


                                }

                            }
                        });
                    }
                } else {
                    btCommit.setVisibility(View.GONE);
                }

                //关闭按钮
                ImageView lvClose = view.findViewById(R.id.lv_close);
                lvClose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //关闭
                        PopUpManager.dismiss();
                    }
                });
            }
        });
    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && busInfo.tkMsg == TkKeys.TKMsg) {
            //取出当前Vp所在的页面的大题对象
            PanelInfo info = panelInfos.get(currPos);
            List<CommitAnswerInfo> commitAnswerInfos = info.commitAnswerInfos;
            //取出作答的小题对象,同步当前小题的作答信息
            int pos = busInfo.tkChoosePos;
            CommitAnswerInfo answerInfo = commitAnswerInfos.get(pos);
            answerInfo.setOnwAnswer(busInfo.tkChooseAnswer);
            answerInfo.setRight(busInfo.tkChooseResult);

            //同步info的状态
            //是否完成的状态同步
            if (hasCompeted(commitAnswerInfos)) {
                //已经做完
                info.state = 1;
            } else {
                //没有做完
                info.state = 0;
            }

            //总分的状态同步
            info.score = getScore(commitAnswerInfos);

            //是否正确的状态同步qa_answer的值
            if (isAllRight(commitAnswerInfos)) {
                info.qa_answer = 1;
            } else {
                info.qa_answer = 0;
            }

            //同步大题中每个小题的正确率
            info.sub_answer = sysSubAnswer(commitAnswerInfos);

            //同步大题中每个小题的具体答案
            info.option_content = sysOptionContent(commitAnswerInfos);

            //判断题目是否全部做完
            if (hasDoneOver(panelInfos)) {
                //显示提交面板的PopUpwindow
                showCommitPanel();
            }
        }

    }


    /**
     * 判断所有大题是否做完的方法
     */
    public boolean hasDoneOver(List<PanelInfo> panelInfos) {
        boolean res = true;
        for (int i = 0; i < panelInfos.size(); i++) {
            if (panelInfos.get(i).state == 0) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 同步大题中每个小题的具体答案的方法
     * 将每个小题的用户自己作答的信息使用￠连接拼串
     */
    public String sysOptionContent(List<CommitAnswerInfo> commitAnswerInfos) {
        String res = "";
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (i == 0) {
                //第一个
                res += commitAnswerInfos.get(i).onwAnswer;
            } else {
                //其它,使用￠+当前自己的作答进行连接
                if ("7".equals(commitAnswerInfos.get(i).getTypeid())) {
                    res += "∩" + commitAnswerInfos.get(i).onwAnswer;
                } else {
                    res += "￠" + commitAnswerInfos.get(i).onwAnswer;
                }
            }
        }
        return res;
    }

    /**
     * 同步大题中每个小题的对错的方法
     * 将每个小题的用户的作答对错使用￠连接拼串
     */
    public String sysSubAnswer(List<CommitAnswerInfo> commitAnswerInfos) {
        String res = "";
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (i == 0) {
                //第一个
                if (commitAnswerInfos.get(i).isRight) {
                    res += "1";
                } else {
                    res += "0";
                }
            } else {
                //其它,使用￠+当前自己的作答进行连接

                if (commitAnswerInfos.get(i).isRight) {
                    res += "￠" + "1";
                } else {
                    res += "￠" + "0";
                }
            }
        }
        return res;
    }

    /**
     * 回传每个大题中所有小题的正确答案的方法
     * 将每个小题的用户的作答对错使用￠连接拼串
     */
    public String sysAnswer(List<CommitAnswerInfo> commitAnswerInfos) {
        String res = "";
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (i == 0) {
                //第一个
                res += commitAnswerInfos.get(i).rightAnser;
            } else {
                //其它,使用￠+当前自己的作答进行连接
                res += "￠" + commitAnswerInfos.get(i).rightAnser;
            }
        }
        return res;
    }

    /**
     * 根据小题是否都作答判断该答题是否做完的方法
     * 返回true做完,返回false没做完
     * 只要小题中onwAnswer有一个是空,则返回false
     */
    public boolean hasCompeted(List<CommitAnswerInfo> commitAnswerInfos) {
        boolean res = true;
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (TextUtils.isEmpty(commitAnswerInfos.get(i).onwAnswer)) {
                res = false;
                break;
            }
        }
        return res;
    }


    /**
     * 根绝每个小题返回当前答题的分数
     * 先判断当前小题是否作答正确,如果正确,则加上该小题的分数
     */
    public int getScore(List<CommitAnswerInfo> commitAnswerInfos) {
        int res = 0;
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (commitAnswerInfos.get(i).isRight) {
                //作答正确
                res += commitAnswerInfos.get(i).score;
            }
        }
        return res;
    }

    /**
     * 根据小题是否都正确来判断该大题是否正确的方法
     * 返回true全部正确,返回false则错误
     * 只要小题中onwAnswer有一个是空,则返回false
     */
    public boolean isAllRight(List<CommitAnswerInfo> commitAnswerInfos) {
        boolean res = true;
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (!commitAnswerInfos.get(i).isRight) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 学生参看答题详情的面板
     */
    private void showErrorPanel() {

        PopUpManager.showPopByMatchParent(this, R.layout.panel_error, 0.3f, this, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                //水波纹控件
                WaveLoadingView wv = view.findViewById(R.id.waveLoadingView);
                wv.setProgressValue(info.score);
                wv.setCenterTitle(info.score + "%");

                //计分规则
                TextView tvJfgz = view.findViewById(R.id.tv_jfgz);
                tvJfgz.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //跳转到计分规则界面
                        UiUtils.startActivity(TeacherTkMainActivity.this, ScoringRuleActivity.class);
                    }
                });

                //时间
                TextView tvTime = view.findViewById(R.id.tv_time);
                tvTime.setText(DateUtils.timeFormat(info.created * 1000));

                //展示答题信息的GridView
                GridView gv = view.findViewById(R.id.gv);

                PanelGvAdapter adapter = new PanelGvAdapter(TeacherTkMainActivity.this, type, commitAnswerInfos, R.layout.tk_gv_item_panel);

                gv.setAdapter(adapter);

                LogUtils.iTag("test", GsonUtil.listToJson(commitAnswerInfos));

                adapter.setOnTvClickListener(new PanelGvAdapter.onTvClickListener() {
                    @Override
                    public void onClick(int pos) {

                        //获取小题所属大题在整个题目的位置
                        int postion = Integer.valueOf(commitAnswerInfos.get(pos).index);

                        //定位答题所在的位置
                        if (postion != currPos) {
                            currPos = postion;
                            vp.setCurrentItem(currPos);
                        }

                        //定位小题所在的位置,先确定大题所处的小题位置,只有大题中有多个小题的才进行翻页处理
                        BusInfo busInfo = new BusInfo();
                        busInfo.type = TkKeys.TKCOMIT;
                        busInfo.bigPos = Integer.parseInt(commitAnswerInfos.get(pos).index);
                        busInfo.postion = Integer.parseInt(commitAnswerInfos.get(pos).num);
                        EventBus.getDefault().post(busInfo);

                        //关闭弹框
                        PopUpManager.dismiss();
                    }
                });


                //关闭按钮
                ImageView lvClose = view.findViewById(R.id.lv_close);
                lvClose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //关闭
                        PopUpManager.dismiss();
                    }
                });
            }
        });
    }

    /**
     * 考虑熄屏
     */
    @Override
    protected void onPause() {
        super.onPause();
        if ("0".equals(type)) {
            TimerCountManager.stopTimer(timer);

            long time = System.currentTimeMillis() - TimeCount.newInstance().getLastTime();

            //计算总用时
            long totalTime = TimeCount.newInstance().getTotalTime() + time;

            //记录总用时
            TimeCount.newInstance().setTotalTime(totalTime);
        }
    }

    /**
     * 考虑亮屏
     */
    @Override
    protected void onRestart() {
        super.onRestart();

        if ("0".equals(type)) {
            if (isNeedCountTime) {
                TimerCountManager.startTimer(false, timer);
            }

            //重置LastTime
            TimeCount.newInstance().setLastTime(System.currentTimeMillis());
        }
    }

    /**
     * 生命周期中停止计时
     */
    @Override
    protected void onDestroy() {
        if ("0".equals(type)) {
            //销毁时停止计时
            TimerCountManager.stopTimer(timer);

            //还原状态
            setIsNeedCountTime(true);

            //还原计时器的时间统计
            TimeCount.release();
        }
        super.onDestroy();
    }

    /**
     * 判断所有大题是否做完的方法
     */
    public boolean hasDoneOver() {
        boolean res = true;
        for (int i = 0; i < panelInfos.size(); i++) {
            if (panelInfos.get(i).state == 0) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 获取上传的时间的方法,返回的是秒
     */
    public String getPostTime() {

        //获取上传时间
        long useTime = TimeCount.newInstance().getTotalTime() + (System.currentTimeMillis() - TimeCount.newInstance().getLastTime());

        //转化为秒
        String seconds = useTime / 1000 + "";

        return seconds;
    }

    /**
     * 获取获得分数的方法
     * 上传的key为score
     */
    public String getMyScore() {
        int res = 0;
        for (int i = 0; i < panelInfos.size(); i++) {

            List<CommitAnswerInfo> commitAnswerInfos = panelInfos.get(i).commitAnswerInfos;

            for (int j = 0; j < commitAnswerInfos.size(); j++) {
                if (commitAnswerInfos.get(j).isRight) {
                    res += commitAnswerInfos.get(j).score;
                }
            }

        }
        return res + "";
    }


    /**
     * 获取上传的总分数的方法
     * 上传的key为score
     */
    public String getTotalScore(List<PanelInfo> panelInfos) {
        int res = 0;
        for (int i = 0; i < panelInfos.size(); i++) {

            List<CommitAnswerInfo> commitAnswerInfos = panelInfos.get(i).commitAnswerInfos;

            for (int j = 0; j < commitAnswerInfos.size(); j++) {
                res += commitAnswerInfos.get(j).score;
            }
        }
        return res + "";
    }


    /**
     * 上传的key为question_list
     * 根据提交面板的数据生成提交需要的json格式数据的方法
     */
    public String getPostJson() {

        List<CommitInfo> commitInfos = new ArrayList<>();

        for (int i = 0; i < panelInfos.size(); i++) {
            CommitInfo info = new CommitInfo();
            info.option_content = panelInfos.get(i).option_content;
            info.right_answer = panelInfos.get(i).right_answer;
            info.qa_answer = panelInfos.get(i).qa_answer;
            info.question_type = panelInfos.get(i).question_type;
            info.question_id = panelInfos.get(i).question_id;
            info.sub_answer = panelInfos.get(i).sub_answer;
            commitInfos.add(info);
        }

        return GsonUtil.listToJson(commitInfos);
    }

}
